﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CPETwit.WPFClient.Helper
{
    public static class ImageLoader
    {
        /// <summary>
        /// Obtient un ImageSource à partir d'un tableau de Bytes.
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static ImageSource GetImageSourceFromBytes(byte[] buffer)
        {
            MemoryStream stream = new MemoryStream(buffer);
            return GetImageSourceFromStream(stream);
        }

        /// <summary>
        /// Obtient un ImageSource à partir d'un Stream.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static ImageSource GetImageSourceFromStream(Stream stream)
        {
            try
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = stream;
                image.EndInit();
                return image;
            }
            catch (Exception)
            {
                return null;
            }
        }
       
        /// <summary>
        /// Méthode qui retourne l'image source par défaut.
        /// </summary>
        /// <returns></returns>
        public static ImageSource GetDefaultImageSource()
        {
            var uriSource = new Uri(@"pack://application:,,,/CPETwit.WPFClient;component/Images/avatarInconnu.jpg");
            BitmapImage defaultImageSource = new BitmapImage(uriSource);
            return defaultImageSource;
        }

        /// <summary>
        /// Obtient un tableau de bytes à partir d'un image source.
        /// </summary>
        /// <param name="imageSource"></param>
        /// <returns></returns>
        public static byte[] GetBytesFromImageSource(ImageSource imageSource)
        {
            if (imageSource is BitmapImage)
                return GetBytesFromBitmapImage(imageSource as BitmapImage);
            return null;
        }

        /// <summary>
        /// Obtient un tableau de bytes à partir d'un bitmap image.
        /// </summary>
        /// <param name="bitmapImage"> </param>
        /// <returns></returns>
        public static byte[] GetBytesFromBitmapImage(BitmapImage bitmapImage)
        {
            MemoryStream memStream = new MemoryStream();
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
            encoder.Save(memStream);
            return memStream.GetBuffer();
        }
    }
}
